package autosession

import (
	"time"

	"github.com/golang-jwt/jwt/v4"
)

var mySigningKey = []byte("growup666")

// 给inspector进行加密和解密的方法
type InspectorEncryptor interface {
	Sign(sessionId string, options *Options) (jwtString string, err error)
	Parse(tokenString string) (string, error)
}

type JwtEncryptor struct {
}

func (e *JwtEncryptor) Sign(sessionId string, options *Options) (jwtString string, err error) {
	claims :=
		jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(options.MaxAge) * time.Second)),
			ID:        sessionId,
		}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// fmt.Printf("write sessionId:%+v\n", sessionId)
	str, err := token.SignedString(mySigningKey)
	// fmt.Printf("write jwt:%+v\n", str)
	return str, err
}

func (e *JwtEncryptor) Parse(tokenString string) (string, error) {
	token, err := jwt.ParseWithClaims(tokenString, &jwt.RegisteredClaims{}, func(token *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})

	if err != nil {
		return "", &NotFoundError{"session解析失败了:" + err.Error()}
	}

	if claims, ok := token.Claims.(*jwt.RegisteredClaims); ok && token.Valid {
		return claims.ID, nil
	}

	return "", &NotFoundError{"session解析失败了"}
}
